//
//  KLPaymentManager.m
//  Meboo
//
//  Created by kyo on 2023/12/28.
//

#import "KLPaymentManager.h"
#import <StoreKit/StoreKit.h>
#import "MBHTTPNetworking.h"
@interface KLPaymentManager ()
<
SKPaymentTransactionObserver,
SKProductsRequestDelegate
>
@property(nonatomic,copy) NSString *orderNo;
@end
@implementation KLPaymentManager
+ (instancetype)sharePaymentManager {
    static KLPaymentManager *paymentInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        paymentInstance = [[KLPaymentManager alloc] init];
    });
    return paymentInstance;
}

//restore purchaase
- (void)restorePurchaase {
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

//pay with id
- (void)payWithProductID:(NSString *)productID {
    [MBProgressHUD showActivityMessageInWindow:@"paying..."];
    self.productID = productID;
    //先请求商品id,成功了继续,失败了不再执行
    [[MBMineDataManager sharedManager] getProductIdWithType:1 productCode:self.productID modelUserCode:self.modelUserCode ?: @"" success:^(BOOL success) {
        if (success && [MBMineDataManager sharedManager].orderNo.length > 0) {
            self.orderNo = [MBMineDataManager sharedManager].orderNo;
            [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
            if([SKPaymentQueue canMakePayments]){
                [self requestProductData:productID];
            }else{
                NSLog(@"不允许程序内付费");
                [MBProgressHUD hideHUD];
                if (self.payBlock) {
                    self.payBlock(NO);
                }
            }
        } else {
            self.orderNo = @"";
            [MBProgressHUD hideHUD];
            if (self.payBlock) {
                self.payBlock(NO);
            }
        }
    }];
}

//去苹果服务器请求商品
- (void)requestProductData:(NSString *)type{
    
    NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
    
    /**
     埋点 code
     支付商品查询结果 312
     */
    [[NSIOApiManager sharedManager] setIOWithCode:@"312" content:@"product ok! request start"];
}

//收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    if(product.count==0){
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showErrorMessage:@"product information not found"];
            [MBProgressHUD hideHUD];
            if (self.payBlock) {
                self.payBlock(NO);
            }
        });
        
        return;
    }
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [MBProgressHUD showActivityMessageInWindow:@"paying..."];
//    });
    
    SKProduct *p = nil;
    for(SKProduct *pro in product) {
        NSLog(@"%@", [pro description]);
        NSLog(@"%@", [pro localizedTitle]);
        NSLog(@"%@", [pro localizedDescription]);
        NSLog(@"%@", [pro price]);
        NSLog(@"%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString: self.productID]){
            p = pro;
        }
    }
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    NSLog(@"发送购买请求");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
//    [IHUtility removeWaitingView];
    [MBProgressHUD hideHUD];
    [MBProgressHUD showErrorMessage:@"payment failure"];
    if (self.payBlock) {
        self.payBlock(NO);
    }
}

- (void)requestDidFinish:(SKRequest *)request{
//    [IHUtility removeWaitingView];
}

//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction {
    /**
     埋点 code
     拉起收银台 300
     */
    [[NSIOApiManager sharedManager] setIOWithCode:@"300" content:@"TRY_TO_PURCHASE"];
    for (SKPaymentTransaction *tran in transaction) {
        
        switch (tran.transactionState) {
                
            case SKPaymentTransactionStatePurchased:
                //交易完成
                // 购买后告诉交易队列，把这个成功的交易移除掉
                [queue finishTransaction:tran];
                
                // 订阅特殊处理
                if (tran.originalTransaction) {
                    // 如果是自动续费的订单,originalTransaction会有内容
                    NSLog(@"自动续费的订单,originalTransaction = %@",tran.originalTransaction);
                } else {
                    // 普通购买，以及第一次购买自动订阅
                    NSLog(@"普通购买，以及第一次购买自动订阅");
                }
                
                [self verifyPurchaseWithPaymentTransactionWith:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                //商品添加进列表(正在购买)
                NSLog(@"商品已经添加进列表");
//                [MBProgressHUD showActivityMessageInWindow:@"paying..."];
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品%@",tran.transactionIdentifier);
//                tran.transactionDate
                //2024-01-03 06:38:57 +0000
//                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                if ([tran.originalTransaction.transactionIdentifier isEqualToString:self.productID]) {
                    [self verifyPurchaseWithPaymentTransactionWith:tran];
                }
                break;
            case SKPaymentTransactionStateFailed:
                if (self.payBlock) {
                    self.payBlock(NO);
                }
                [MBProgressHUD hideHUD];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                /**
                 埋点 code
                 购买流程中报错 313
                 */
                [[NSIOApiManager sharedManager] setIOWithCode:@"313" content:@"apple pay cancel"];
                break;
            case SKPaymentTransactionStateDeferred:
            {
                NSLog(@"交易还在队列里面，但最终状态还没有决定");
            }
                break;
            default:
                break;
        }
    }
}

//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
}

// 恢复成功后的回调
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    NSMutableArray *buyIDArr = [NSMutableArray array];
   if (queue.transactions.count) {
       for (SKPaymentTransaction *tran in queue.transactions) {
//           if (tran.originalTransaction.transactionIdentifier) {
////               [self saveOrderId:tran.originalTransaction.transactionIdentifier];
//               break;
//           }
           if ([tran.payment.productIdentifier isEqualToString:self.productID]) {
               [buyIDArr addObject:tran];
           }
       }
       if (buyIDArr.count) {
           [self restorePurchaseInfo:buyIDArr.lastObject];
       }
       /**
        埋点 code
        拉起收银台 311
        */
       [[NSIOApiManager sharedManager] setIOWithCode:@"311" content:@"apple pay success"];
   } else {
       // 没有可恢复的购买项
       NSLog(@"");
       /**
        埋点 code
        支付失败 314
        */
       [[NSIOApiManager sharedManager] setIOWithCode:@"314" content:@"apple pay fail"];
   }
}

//拿最后一个处理事件
- (void)restorePurchaseInfo:(SKPaymentTransaction *)tran {
    //验证一下这个单 曾经的单
    if ([tran.payment.productIdentifier isEqualToString:self.productID]) {
        [self verifyPurchaseWithPaymentTransactionWith:tran];
    }
}

///验证购买，避免越狱软件模拟苹果请求达到非法购买问题
-(void)verifyPurchaseWithPaymentTransactionWith:(SKPaymentTransaction *)tran{
    [MBProgressHUD hideHUD];
    [MBProgressHUD showActivityMessageInWindow:@"Payment Processing"];
    NSString *transactionIdentifier = tran.transactionIdentifier;
    NSString * productIdentifier = tran.payment.productIdentifier;
    NSLog(@"productIdentifier Product id：%@", productIdentifier);
    
    NSString *transactionReceiptString = nil;
    
    //系统IOS7.0以上获取支付验证凭证的方式应该改变，切验证返回的数据结构也不一样了。
    NSString *version = [UIDevice currentDevice].systemVersion;
    if([version intValue] >= 7.0){
        // 验证凭据，获取到苹果返回的交易凭据
        // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址(从沙盒中获取交易凭证并且拼接成请求体数据)
        NSURLRequest * appstoreRequest = [NSURLRequest requestWithURL:[[NSBundle mainBundle]appStoreReceiptURL]];
        NSError *error = nil;
        NSData * receiptData = [NSURLConnection sendSynchronousRequest:appstoreRequest returningResponse:nil error:&error];
        
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receiptData options:NSJSONReadingMutableContainers error:&error];
        
//        transactionReceiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        transactionReceiptString = [receiptData base64EncodedStringWithOptions:0];
    }else{
        
        NSData * receiptData = tran.transactionReceipt;
        //  transactionReceiptString = [receiptData base64EncodedString];
        transactionReceiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    }
    // 去验证是否真正的支付成功了
    [self checkApplePayWithOrderId:transactionIdentifier receiptStr:transactionReceiptString];
}

-(void)checkApplePayWithOrderId:(NSString *)orderId receiptStr:(NSString *)receiptStr {
    //支付信息存下来 receiptStr:回执信息 requestNum:重复请求次数 orderID:订单号 productID:商品id
    MBUserAccount *account = [MBUserAccount defaultAccount];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:receiptStr forKey:@"receiptStr"];
    [dict setValue:self.orderNo forKey:@"orderNo"];
    [dict setValue:orderId forKey:@"orderID"];
    [dict setValue:self.productID forKey:@"productID"];
    [dict setValue:@"0" forKey:@"requestNum"];
    if (!account.receiptDataArr) {
        account.receiptDataArr = [NSMutableArray array];
    }
    [account.receiptDataArr addObject:dict];
    [MBUserAccount saveAccount:account];
    
//    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//    [params setObject:receiptStr forKey:@"receipt-data"];
////    [params setObject:@"13ccdd4b6df549a583b85579eca77839" forKey:@"password"];
//    [[MBHTTPNetworking sharedInstance] WSAFNoOAuthUrlString:@"https://sandbox.itunes.apple.com/verifyReceipt" method:@"POST" parameters:params success:^(id  _Nullable responseObject) {
//        NSInteger code = [responseObject[@"code"] integerValue];
//        if (code == 0) {
//            NSLog(@"");
//        } else {
//            NSLog(@"");
//        }
//    } failure:^(NSError * _Nullable error) {
//        NSLog(@"");
//    }];
    

    
    [[MBMineDataManager sharedManager] checkApplePayWith:self.productID orderNo:self.orderNo orderId:orderId payReceipt:receiptStr Success:^(NSInteger state) {
        //支付步骤结束
        [MBProgressHUD hideHUD];
        if (state == 0) {
            if (self.payBlock) {
                self.payBlock(YES);
            }
//            [MBProgressHUD showSuccessMessage:@"Pay Success"];
            [account.receiptDataArr removeObject:dict];
            [MBUserAccount saveAccount:account];
        } else if (state == 1) {
            if (self.payBlock) {
                self.payBlock(NO);
            }
            [MBProgressHUD showErrorMessage:@"Pay Failure"];
            [account.receiptDataArr removeObject:dict];
            [MBUserAccount saveAccount:account];
        } else {
            if (self.payBlock) {
                self.payBlock(NO);
            }
            [MBProgressHUD showErrorMessage:@"Network Error"];
        }
        
        if (state < 2) {
            [account.receiptDataArr removeObject:dict];
            [MBUserAccount saveAccount:account];
        }
    }];
}

//掉单重试
- (void)reVerifyReceiptData {
    MBUserAccount *account = [MBUserAccount defaultAccount];
    if (account.receiptDataArr.count == 0) {
        return;
    } else {
    //receiptStr:回执信息 requestNum:重复请求次数 orderID:订单号 productID:商品id
        for (int i = 0; i<account.receiptDataArr.count; i++) {
            NSMutableDictionary *dict = account.receiptDataArr[i];
            NSInteger num = [dict[@"requestNum"] integerValue];
            [[MBMineDataManager sharedManager] checkApplePayWith:dict[@"productID"] orderNo:dict[@"orderNo"] orderId:dict[@"orderID"] payReceipt:dict[@"receiptStr"] Success:^(NSInteger state) {
                if (state < 2 || num >= 4) {
                    [account.receiptDataArr removeObjectAtIndex:i];
                    [MBUserAccount saveAccount:account];
                } else {
                    [dict setValue:[NSString stringWithFormat:@"%ld",num+1] forKey:@"requestNum"];
                    [account.receiptDataArr replaceObjectAtIndex:i withObject:dict];
                }
                [MBUserAccount saveAccount:account];
            }];
        }
    }
}



- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end
